package net.kehuilai.tools;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by genghz on 16/12/22.
 */
public class CookieTool {

    public static final int YEAR = 31536000;
    public static final int MONTH = 25920000;
    public static final int DAY = 86400;
    public static final int CLOSE_DIE = -1;

    public static boolean setCookie(String key, String value, int expire, HttpServletResponse response) {
        return setCookie(key, value, expire, null, response);
    }

    public static boolean setCookie(String key, String value, int expire, String domain, HttpServletResponse response) {

        if (key == null || key.isEmpty() || value == null || value.isEmpty() || response == null)
            return false;

        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(expire);
        cookie.setPath("/");
        if (domain != null && !domain.isEmpty()) cookie.setDomain(domain);

        response.addCookie(cookie);
        return true;
    }

    public static String getCookie(String key, HttpServletRequest request) {
        String value = "";

        if (key == null || key.isEmpty() || request == null)
            return value;

        Cookie[] cookies = request.getCookies();
        if (cookies == null) return value;

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(key)) {
                return cookie.getValue();
            }
        }
        return value;
    }

    public static void delCookie(String key, HttpServletResponse response) {
        delCookie(key, null, response);
    }

    public static void delCookie(String key, String domain, HttpServletResponse response) {
        if (key == null || key.isEmpty() || response == null)
            return;
        Cookie cookie = new Cookie(key, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        if (domain != null && !domain.isEmpty()) cookie.setDomain(domain);

        response.addCookie(cookie);
    }
}
